package com.mutual.commom.wechat;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class PayCommonUtil {



    /**
     * 创建微信交易对象
     * ml="<xml>"+
	            "<appid>"+ APPID+"</appid>"+
	            "<mch_id>"+ MERID+"</mch_id>"+
	            "<nonce_str>"+nonce_str+"</nonce_str>"+
	            "<sign>"+sign+"</sign>"+
	            "<body>"+subject+"</body>"+//
	            "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
	            "<total_fee>"+finalmoney+"</total_fee>"+//
	            "<trade_type>"+tradeType+"</trade_type>"+
	            "<notify_url>"+"这里写回调地址"+"</notify_url>"+
	            "<sign_type>MD5</sign_type>"+
	            "<scene_info>"+scene_info+"</scene_info>"+
	            "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
	            "</xml>";
	            
	            String sign = PayCommonUtil.createSign("UTF-8", parameters);
	        parameters.put("sign", sign);

--------------------- 
作者：诗和远方zdx 
来源：CSDN 
原文：https://blog.csdn.net/u010212399/article/details/81185075 
版权声明：本文为博主原创文章，转载请附上博文链接！
     * 
     */
    public static SortedMap<String, String> getWXPrePayID(String tradeType, String openid) {
        SortedMap<String, String> parameters = new TreeMap<String, String>();
        parameters.put("appid", ConstantUtil.APP_ID);
        parameters.put("mch_id", ConstantUtil.MCH_ID);
        parameters.put("nonce_str", createNoncestr());
        parameters.put("fee_type", "CNY");
        parameters.put("notify_url", "http://www.baidu.com");
        parameters.put("trade_type", org.springframework.util.StringUtils.isEmpty(tradeType) ? "APP" : tradeType);
        return parameters;
    }

    /**
     * 再次签名（仅APP支付需要）
     */
    public static SortedMap<String, String> startWXPay(Map<String,String> map) {
        try {

            SortedMap<String, String> parameterMap = new TreeMap<String, String>();
            parameterMap.put("appid", ConstantUtil.APP_ID);
            parameterMap.put("partnerid", ConstantUtil.MCH_ID);
            parameterMap.put("prepayid", map.get("prepay_id"));
            parameterMap.put("package", "Sign=WXPay");
            parameterMap.put("noncestr", createNoncestr());
            // 10位
            parameterMap.put("timestamp",
                    String.valueOf(Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10))));
            String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
            parameterMap.put("sign", sign);
            return parameterMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    * 获取真实IP
    * */
    public static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     * 创建随机数
     *
     * @param length
     * @return
     */
    public static String createNoncestr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }
    
    public static void main(String[] args) {
		System.out.println("Guanaichou2019".length());
	}

    /**
     * @param characterEncoding 编码格式
     * @param parameters        请求参数
     * @return
     * @Description：创建sign签名
     */
    public static String createSign(String characterEncoding, SortedMap<String, String> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + ConstantUtil.APP_KEY);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    
  //将封装好的参数转换成Xml格式类型的字符串

    public static String getRequestXml(SortedMap<String,String> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if("sign".equalsIgnoreCase(k)){

            }
            else if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }
            else {
                sb.append("<"+k+">"+v+"</"+k+">");
            }
        }
        sb.append("<"+"sign"+">"+"<![CDATA["+parameters.get("sign")+"]]></"+"sign"+">");
        sb.append("</xml>");
        return sb.toString();
    }
    
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
   /**
	 * HTTP Get 获取内容
	 * @param url请求的url地址 ?之前的地址
	 * @param params请求的参数
	 * @param charset编码格式
	 * @return 页面内容
	 */
	public static String sendGet(String url, Map<String, Object> params){
		CloseableHttpResponse response=null;
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();

			if (params != null && !params.isEmpty()) {

				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());

				for (String key : params.keySet()) {
					pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
				}
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs), "UTF-8");
			}

			HttpGet httpGet = new HttpGet(url);
			response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
				EntityUtils.consume(entity);
				response.close();
				return result;
			} else {
				return null;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(response!=null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

